import { Component, OnInit, ViewChild } from '@angular/core';
import { STColumn, STComponent } from '@delon/abc/st';
import { SFComponent, SFDateWidgetSchema, SFSchema, SFSelectWidgetSchema, SFUISchema } from '@delon/form';
import { map } from 'rxjs/operators';
import { ShipperBaseService } from '@shared';
import { InterfaceDockingService } from '../../services/interface-docking.service';
import { NzModalService } from 'ng-zorro-antd/modal';
import { VehicleConfirReceiptComponent } from '../../../order-management/modal/vehicle/confir-receipt/confir-receipt.component';
import { settingVehicleEditComponent } from '../set/edit.component';
import { confirReceiptComponent } from '../confir-receipt/confir-receipt.component';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-interface-docking-waybill',
  templateUrl: './load.component.html',
  styleUrls: ['./load.component.less']
})
export class interfaceDockingLoadComponent implements OnInit {
  ui: SFUISchema = {};
  uiView: SFUISchema = {};
  schema: SFSchema = {};
  schemaView: SFSchema = {};
  auditMany = false;
  isVisibleView = false;
  isVisibleEvaluate = false;
  _$expand = false;
  isVisible = false;
  @ViewChild('st') private readonly st!: STComponent;
  @ViewChild('stFloat') private readonly stFloat!: STComponent;
  @ViewChild('stFloatView') private readonly stFloatView!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('sfFre', { static: false }) sfFre!: SFComponent;
  @ViewChild('sfView', { static: false }) sfView!: SFComponent;
  columns: STColumn[] = [];
  resourceStatus: any;
  constructor(
    public service: InterfaceDockingService,
    public shipperservice: ShipperBaseService,
    private nzModalService: NzModalService,
    private router: Router,
    private ar: ActivatedRoute
  ) {}

  /**
   * 查询参数
   */
  get reqParams() {
    const a: any = {};
    if (this.resourceStatus) {
      a.billStatus = this.resourceStatus;
    }
    const params: any = Object.assign({}, this.sf?.value || {});
    delete params._$expand;
    return {
      ...a,
      ...params,
      createTime: {
        start: this.sf?.value?.createTime?.[0] || '',
        end: this.sf?.value?.createTime?.[1] || ''
      },
      etd: {
        start: this.sf?.value?.etd?.[0] || '',
        end: this.sf?.value?.etd?.[1] || ''
      }
    };
  }
  get selectedRows() {
    return this.st?.list.filter(item => item.checked) || [];
  }
  search() {
    this.st?.load(1);
  }
  initSF() {
    this.schema = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        blLoadNo: {
          type: 'string',
          title: '派车单号'
        },
        startPlace: {
          type: 'string',
          title: '起始地'
        },
        endPlace: {
          type: 'string',
          title: '目的地'
        },
        loadStatus: {
          type: 'string',
          title: '派车单状态',
          enum: [
            { label: '全部', value: null },
            { label: '已发布', value: '已发布' },
            { label: '已取消', value: '已取消' },
            { label: '已派车', value: '已派车' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          }
        },
        createTime: {
          title: '创建时间',
          type: 'string',
          ui: {
            widget: 'date',
            mode: 'range',
            format: 'yyyy-MM-dd',
            allowClear: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        },
        etd: {
          title: '计划发货时间',
          type: 'string',
          ui: {
            widget: 'date',
            mode: 'range',
            format: 'yyyy-MM-dd',
            allowClear: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        }
      },
      type: 'object'
    };
    this.ui = { '*': { spanLabelFixed: 110, grid: { span: 8, gutter: 4 } } };
  }

  ngOnInit(): void {
    this.initSF();
    this.initST();
  }

  // 获取城市列表
  getRegionCode(regionCode: any) {
    console.log(regionCode);
    return this.service
      .request(this.service.$api_get_enterprise_project, { id: regionCode })
      .pipe(
        map(res =>
          res.map((item: any) => ({
            label: item.projectName,
            value: item.id
          }))
        )
      )
      .subscribe(res => {
        this.sf.getProperty('/enterpriseProjectId')!.schema.enum = res;
        this.sf.getProperty('/enterpriseProjectId')!.widget.reset(res);
      });
  }
  /**
   * 初始化数据列表
   */
  initST() {
    this.columns = [
      { title: '', type: 'checkbox', fixed: 'left', width: '50px', className: 'text-center' },
      {
        title: '派车单号',
        width: '300px',
        fixed: 'left',
        className: 'text-left',
        render: 'blLoadNo',
        index: 'blLoadNo'
      },
      {
        title: '车辆类型',
        width: '180px',
        className: 'text-left',
        index: 'vehicleType'
      },
      {
        title: '派车单状态',
        width: '180px',
        className: 'text-center',
        index: 'loadStatus'
      },
      {
        title: '箱类型',
        width: '180px',
        className: 'text-left',
        index: 'ctnTypeZise'
      },
      { title: '计划发货时间', index: 'etd', width: '220px', className: 'text-left' },
      { title: '创建时间', index: 'createTime', width: '220px', className: 'text-left' },
      { title: '件数', index: 'qty', width: '220px', className: 'text-left' },
      { title: '重量', index: 'grossWeight', width: '180px', className: 'text-left' },
      { title: '体积', index: 'cubic', width: '180px', className: 'text-left' },
      { title: '保价', index: 'cargoValue', width: '180px', className: 'text-left' },
      { title: '短驳', index: 'shortFlag', width: '180px', className: 'text-left' },
      { title: '运输方式', index: 'offeringType', width: '180px', className: 'text-left' },
      { title: '备注', index: 'notes', width: '180px', className: 'text-left' },
      { title: '行程公里数', index: 'distance', width: '180px', className: 'text-left' },
      { title: '预计运输时长', index: 'distanceTime', width: '180px', className: 'text-left' },
      {
        title: '操作',
        fixed: 'right',
        width: '150px',
        className: 'text-center block-td',
        buttons: [
          {
            text: '填写司机信息',
            iif: (item) => {
              if(item.loadStatus != '已取消') {
                return true
              }
             return false
            },
            click: _record => this.saveVehicleInfo(_record),
            acl: { ability: ['INTERFACE-LIST-LOAD-billSearch'] }
          },
          {
            text: '查看运单',
            iif: (item) => {
              if(item.loadStatus != '已取消') {
                return true
              }
              return false
            },
            click: (item: any) => {
              this.router.navigate(['/interface-docking/list'], { queryParams: { blLoadNo: item.blLoadNo } });
            }
          }
        ]
      }
    ];
  }
  /**
   * 查询字段个数
   */
  get queryFieldCount(): number {
    return Object.keys(this.schema?.properties || {}).length;
  }

  tabChange(item: any) {}
  /**
   * 重置表单
   */
  resetSF(): void {
    this.sf.reset();
    this._$expand = false;
  }

  /**
   * 修改司机信息
   */
  saveVehicleInfo(value: any) {
    let blNoNo: any = {};
    this.service.request(this.service.$api_waybillInfo_list, { blLoadNo: value.blLoadNo }).subscribe(res => {
      blNoNo = res;
      const modal = this.nzModalService.create({
        nzContent: settingVehicleEditComponent,
        nzWidth: 900,
        nzComponentParams: { params: blNoNo.records },
        nzFooter: null
      });
      modal.afterClose.subscribe(res => {
        if (res) {
          this.st.load();
        }
      });
    });
  }

  /**
   * 伸缩查询条件
   */
  expandToggle(): void {
    this._$expand = !this._$expand;
    this.sf?.setValue('/_$expand', this._$expand);
  }
}
